// 创建命名管道

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "comm.hpp"

int main()
{
    //权限掩码
    umask(0);
    //创建命名管道
    int n = mkfifo(FIFO_FIFO,0666);
    if(n < 0)
    {
        std::cout<<"mkfifo error"<<std::endl;
        return 1;
    }
    std::cout<<"mkfifo successful"<<std::endl;

    //打开文件
    int fd = open(FIFO_FIFO,O_RDONLY);
    if(fd < 0)
    {
        std::cout<<"open fifo error"<<std::endl;
        return 2;
    }
    std::cout<<"open fifo successful"<<std::endl;

    //读
    while(true)
    {
        char buffer[1024];
        int number = read(fd,buffer,sizeof(buffer)-1);
        if(number > 0)
        {
            buffer[number] = 0;
            std::cout<<"client say:"<<buffer<<std::endl;
        }
        else if(number == 0)
        {
            std::cout<<"ending"<<std::endl;
            break;
        }
        else
        {
            std::cout<<"read failed"<<std::endl;
            break;
        }
      

    }

    //关闭文件
    close(fd);


    //删除管道文件
    n = unlink(FIFO_FIFO);
    if(n == 0)
    {
        std::cout<<"remove mkfifo successful"<<std::endl;
    }
    else
    {
        std::cout<<"remove mkfifo failed"<<std::endl;
        return 2;
    }
    return 0;
}